import React, { Component } from 'react'
import { API, BASE_URL } from '../../utils'
import { Link } from 'react-router-dom'
import { Toast } from 'antd-mobile'
import NavHeader from '../../components/NavHeader'
import HouseItem from '../../components/HouseItem'
import NoHouse from '../../components/NoHouse'

import styles from './index.module.css'

class Favorites extends Component {
  state = {
    //收藏房源列表
    list: [],
    isLoading: false,
  }

  //获取收藏房源
  getFavoritesList = async () => {
    Toast.loading('Loading....', 0, null, false)
    this.setState({
      isLoading: true,
    })
    const res = await API.get('/user/favorites')
    Toast.hide()
    const { status, body } = res.data
    if (status === 200) {
      this.setState({
        list: body,
        isLoading: false,
      })
    } else {
      return
    }
  }

  //渲染收藏房源列表
  renderFavoritesList = () => {
    const { list, isLoading } = this.state
    const hasHouses = list.length > 0

    if (!hasHouses && !isLoading) {
      return (
        <NoHouse>
          您还没有收藏房源，
          <Link to="/home/list" className={styles.link}>
            去收藏房源
          </Link>
          吧~
        </NoHouse>
      )
    }

    return <div className={styles.houses}>{this.renderFavoritesItem()}</div>
  }

  //渲染单个收藏房源
  renderFavoritesItem() {
    const { list } = this.state
    const { history } = this.props

    return list.map((item) => {
      return (
        <HouseItem
          key={item.houseCode}
          onClick={() => history.push(`/detail/${item.houseCode}`)}
          src={BASE_URL + item.houseImg}
          title={item.title}
          desc={item.desc}
          tags={item.tags}
          price={item.price}
        />
      )
    })
  }

  componentDidMount() {
    this.getFavoritesList()
  }

  render() {
    const { history } = this.props
    return (
      <div className={styles.root}>
        <NavHeader
          onLeftClick={() => history.go(-1)}
          title="我的收藏"
          className={styles.navHeader}
        ></NavHeader>

        {this.renderFavoritesList()}
      </div>
    )
  }
}

export default Favorites
